using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;


namespace FrameworkQ.ObjectSpace.Data.Schema
{

    public class ForiegnKeyAttribute :  ConstraintAttribute
    {
        private Type _ObjectType;
        private string _KeyField;
        private string _ObjectName;

        public ForiegnKeyAttribute(Type foriegnObject) : base (ConstraintHelper.GenerateForiegnKey)
        {
            _ObjectType = foriegnObject;
            this.SetKey(foriegnObject);
        }

        private void SetKey(Type ObjectType)
        {
            _ObjectName = ObjectType.Name;
            // get all properties
            PropertyInfo[] infos = ObjectType.GetProperties();
            // iterate
            foreach (PropertyInfo info in infos)
            {
                PrimaryKeyAttribute primaryKey = Util.CommonHelper.GetAttribute<PrimaryKeyAttribute>(info);
                // if not null
                if (primaryKey != null)
                {
                    _KeyField = info.Name;
                    break;   
                }
            }
        }

        public ForiegnKeyAttribute(Type foriegnObject, string keyField)
            : base(ConstraintHelper.GenerateForiegnKey)
        {
            _ObjectType = foriegnObject;
            _KeyField = keyField;
        }

        public string ForiegnKeyField
        {
            get { return _KeyField; }
        }

        public string EntityName
        {
            get { return _ObjectName; }
        }
    }
}
